package com.leesche.zcsp.node.net.service.impl;

import com.leesche.zcsp.node.net.service.NetService;
import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;
import org.springframework.web.context.ServletContextAware;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

@Service
public class StartupServiceImpl implements ApplicationContextAware,
		ServletContextAware,
		InitializingBean, ApplicationListener<ContextRefreshedEvent>,
		ServletContextListener {

	private static final Logger LOGGER = Logger
			.getLogger(StartupServiceImpl.class);
	private static ServletContext sContext = null;

	@Autowired
	NetService netService;

	@Override
	public void setApplicationContext(ApplicationContext ctx)
			throws BeansException {
		LOGGER.info("start node server");
		netService.initAliyun();
	}

	public static ServletContext getContext() {
		return sContext;
	}

	@Override
	public void setServletContext(ServletContext context) {
		sContext = context;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
	}

	@Override
	public void onApplicationEvent(ContextRefreshedEvent evt) {
		if (evt.getApplicationContext().getParent() == null) {
		}
	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		if (netService != null)
			netService.closeAliyun();
	}

}
